package com.infolab.scheduler.service;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.rpc.ServiceException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;

import client.MediatorDataInterfaceImpl;
import client.MediatorDataInterfaceImplPort;
import client.MediatorDataInterfaceImpl_Impl;

import com.infolab.aims.GlobalConstant;
import com.infolab.aims.common.CommonUtil;
import com.infolab.aims.service.intf.AssetModelService;
import com.infolab.scheduler.domain.IntfDriver;
import com.infolab.scheduler.domain.IntfPartReplacement;
import com.infolab.scheduler.domain.IntfTaxiDowntime;
import com.infolab.scheduler.service.intf.SchedulerService;

@Service
@Transactional
public class SchedulerServiceImpl implements SchedulerService{

	Log logger = LogFactory.getLog(getClass());
	@PersistenceContext
	private EntityManager em;
	@Autowired
	private AssetModelService assetModelService;
	
	//private String fmsInterfaceUrl  = "http://192.168.32.150:8888/mediator/mediator?wsdl";
	
	private @Value("${fmsInterfaceUrl:\"\"}") String fmsInterfaceUrl;
	
	
	public void updateInterfaceDrivers() {
		
		logger.info("Starting intf updateInterfaceDrivers" );		
		logger.info("--------------------------Executing intf updateInterfaceDrivers-------------------------------------------------");
		
		String autoSeqID="";
		Query query = em.createQuery("from IntfDriver where status is null");
		List<IntfDriver> intfDriverList = query.getResultList();
		logger.info(".... Inside updateInterfaceDrivers -- intfDriverList.size() >>>"+intfDriverList.size());
		logger.info("Total number of driver details="+intfDriverList.size());
		
		if(intfDriverList.size() > 0)
		{
			try {
				Integer nextVal = (Integer) em.createNativeQuery("select nextval('AMSQ_INTF_DRIVER_HEADERID') from dual").getSingleResult();
				autoSeqID = nextVal.toString();
				for(int i=autoSeqID.length();i<7;i++)
				{
					autoSeqID="0"+autoSeqID;
				}
				autoSeqID="AIMS_FMS_"+autoSeqID;
			} catch (Exception e) {
				
				logger.error(CommonUtil.getStackTrace(e));
			}
			logger.info("Sequence ID="+autoSeqID);
			
			String xmlInput=generateDriverXML(intfDriverList,autoSeqID);
			
			String xmlOutput ="";
		
		try{
			
			if(!fmsInterfaceUrl.equalsIgnoreCase("") && fmsInterfaceUrl != null)
			{
			
			MediatorDataInterfaceImpl service = new MediatorDataInterfaceImpl_Impl(fmsInterfaceUrl);
			MediatorDataInterfaceImplPort port = service.getMediatorDataInterfaceImplPort();
			xmlOutput = port.processInfo("storeInfo", xmlInput);
			 
			    //String xmlOutput = processedError();
				//String xmlOutput = finalOutput();
			    //String xmlOutput = generalError();
			    //String xmlOutput = ack();
				
				IntfDriver intfDriver=null;
				try {
					
					String fmsUpdateStatus = loadXMLFromString(xmlOutput);
									
					//Successfully received acknowledgment
					if(fmsUpdateStatus.equalsIgnoreCase("Data Received"))
					{
						logger.info("..updateInterfaceDrivers - Successfully received Acknowledgement from FMS..");
					}
		    		//successfully updated into FMS
					else if(fmsUpdateStatus.equalsIgnoreCase("success"))
					{
					 
					  for(int i=0;i<intfDriverList.size();i++)
					  {
						  intfDriver = new IntfDriver();
						  intfDriver = (IntfDriver)intfDriverList.get(i);
						  IntfDriver newIntfDriver = em.find(IntfDriver.class, intfDriver.getIntfDriverId());						
						  intfDriver.setStatus(GlobalConstant.SUCCESS_VALUE);	
						  intfDriver.setDateExecuted(new Date());
						  BeanUtils.copyProperties(intfDriver,newIntfDriver);						
						  em.merge(newIntfDriver);	
						  
					  }
					 				  
					  logger.info("...updateInterfaceDrivers - Update Successfully to FMS....");
					}
					//process error
					else if(fmsUpdateStatus.equalsIgnoreCase("Unsuccessful"))
					{
						//getDriverDAO().updateDriverDetails(GlobalConstants.FAIL_VALUE,statusID,"Process Error,update Unsuccessful.");
						logger.error("updateInterfaceDrivers - Process Error,update Unsuccessful.");
						logger.error("updateInterfaceDrivers - Here's the incoming xml from FMS:\n\n" + xmlOutput);
						
						 for(int i=0;i<intfDriverList.size();i++)
						  {
							  intfDriver = new IntfDriver();
							  intfDriver = (IntfDriver)intfDriverList.get(i);
							  IntfDriver newIntfDriver = em.find(IntfDriver.class, intfDriver.getIntfDriverId());						
							  intfDriver.setStatus(GlobalConstant.FAILURE_VALUE);	
							  BeanUtils.copyProperties(intfDriver,newIntfDriver);						
							  em.merge(newIntfDriver);	
							  
						  }
					}
					//General Error
					else if(fmsUpdateStatus.equalsIgnoreCase("General Error"))
					{
						//getDriverDAO().updateDriverDetails(GlobalConstants.FAIL_VALUE,statusID,"General Error,update Unsuccessful.");
						logger.error("updateInterfaceDrivers - General Error,update Unsuccessful.");
						logger.error("updateInterfaceDrivers - Here's the incoming xml from FMS:\n\n" + xmlOutput);
						 for(int i=0;i<intfDriverList.size();i++)
						  {
							  intfDriver = new IntfDriver();
							  intfDriver = (IntfDriver)intfDriverList.get(i);
							  IntfDriver newIntfDriver = em.find(IntfDriver.class, intfDriver.getIntfDriverId());						
							  intfDriver.setStatus(GlobalConstant.FAILURE_VALUE);	
							  BeanUtils.copyProperties(intfDriver,newIntfDriver);						
							  em.merge(newIntfDriver);	
							  
						  }
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					logger.error(CommonUtil.getStackTrace(e));
				}
		}
		else{
			logger.error("updateInterfaceDrivers - Pls do check FMS Interface URL. It is blank and not having a valid URL.");			
		}
	}
		catch (IOException e) {
			// TODO Auto-generated catch block
			logger.error(CommonUtil.getStackTrace(e));
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			logger.error(CommonUtil.getStackTrace(e));
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error(CommonUtil.getStackTrace(e));
		}
			
			
			
			
		}
		else
		{
			logger.info("There is no new Driver record from AIMS to update in FMS...");
		}
		
		logger.info("--------------------------Exiting intf updateInterfaceDrivers-------------------------------------------------");

			
		
	}
	
	public String generateDriverXML(List<IntfDriver> intfDriverList,String autoSeqID)
	{
		
		String xmlString="";
				
		 try {
	           
			   IntfDriver intfDriver=new IntfDriver();
	            //Creating an empty XML Document

	            //We need a Document
	            DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
	            DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
	            Document doc = docBuilder.newDocument();
	           
	            //Creating the XML tree

	            //create the root element and add it to the document
	            Element root = doc.createElement("dataInterface");
	            doc.appendChild(root);


	            //create child element, add an attribute, and add to root
	            Element header = doc.createElement("header");
	           // child.setAttribute("name", "value");
	            root.appendChild(header);
	            
	            Element id=doc.createElement("id");
	            header.appendChild(id);
	            Text text = doc.createTextNode(autoSeqID);
	            id.appendChild(text);
	           
	            Element from=doc.createElement("from");
	            header.appendChild(from);
	            text = doc.createTextNode("AIMS");
	            from.appendChild(text);
	            
	            Element to=doc.createElement("to");
	            header.appendChild(to);
	            text = doc.createTextNode("FMS");
	            to.appendChild(text);
	            
	            Element interfaceType=doc.createElement("interfaceType");
	            header.appendChild(interfaceType);
	            text = doc.createTextNode("AIMS_FMS_UPDATE_DRIVER");
	            interfaceType.appendChild(text);
	            
	            Calendar cal=Calendar.getInstance();
	            
	            Element sentTime=doc.createElement("sentTime");
	            header.appendChild(sentTime);
	            text = doc.createTextNode(dateTimeToString(cal));
	            sentTime.appendChild(text);
	            
	            Element numOfEntries=doc.createElement("numOfEntries");
	            header.appendChild(numOfEntries);
	            text = doc.createTextNode(""+intfDriverList.size());
	            numOfEntries.appendChild(text);
	            
	            Element deliveryMode=doc.createElement("deliveryMode");
	            header.appendChild(deliveryMode);
	            text = doc.createTextNode("synchronously");
	            deliveryMode.appendChild(text);
	            
	            Element concurrency=doc.createElement("concurrency");
	            header.appendChild(concurrency);
	            text = doc.createTextNode("true");
	            concurrency.appendChild(text);
	            
	            Element content = doc.createElement("content");
	            root.appendChild(content);
	            intfDriver =new IntfDriver();
	            
	            for(int i=0;i<intfDriverList.size();i++)
				 {
				            	intfDriver=(IntfDriver)intfDriverList.get(i);
				            
				            Element contentItem=doc.createElement("contentItem");
				            content.appendChild(contentItem);
				            
				            Element field=doc.createElement("field");
				            contentItem.appendChild(field);
				            
				            Element fieldName=doc.createElement("fieldName");
				            field.appendChild(fieldName);
				            text = doc.createTextNode("driverIc");
				            fieldName.appendChild(text);
				            
				            Element fieldValue=doc.createElement("fieldValue");
				            field.appendChild(fieldValue);
				            text = doc.createTextNode(intfDriver.getDriverNric());
				            fieldValue.appendChild(text);
				            
				            Element field1=doc.createElement("field");
				            contentItem.appendChild(field1);
				            
				            Element fieldName1=doc.createElement("fieldName");
				            field1.appendChild(fieldName1);
				            text = doc.createTextNode("contactNo");
				            fieldName1.appendChild(text);
				            
				            Element fieldValue1=doc.createElement("fieldValue");
				            field1.appendChild(fieldValue1);
				            text = doc.createTextNode(intfDriver.getDriverTelephoneNo()!=null?intfDriver.getDriverTelephoneNo():"");
				            fieldValue1.appendChild(text);
				            
				            Element field3=doc.createElement("field");
				            contentItem.appendChild(field3);
				            
				            Element fieldName2=doc.createElement("fieldName");
				            field3.appendChild(fieldName2);
				            text = doc.createTextNode("email");
				            fieldName2.appendChild(text);
				            
				            Element fieldValue2=doc.createElement("fieldValue");
				            field3.appendChild(fieldValue2);
				            text = doc.createTextNode(intfDriver.getDriverEmail()!=null?intfDriver.getDriverEmail():"");
				            fieldValue2.appendChild(text);
				}
	            /////////////////
	            //Output the XML

	            //set up a transformer
	            TransformerFactory transfac = TransformerFactory.newInstance();
	            Transformer trans = transfac.newTransformer();
	            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
	            trans.setOutputProperty(OutputKeys.INDENT, "yes");

	            //create string from xml tree
	            StringWriter sw = new StringWriter();
	            StreamResult result = new StreamResult(sw);
	            DOMSource source = new DOMSource(doc);
	            trans.transform(source, result);
	            xmlString = sw.toString();

	            //print xml
	           logger.info("Here's the xml:\n\n" + xmlString);

	        } catch (Exception e) {
	        	logger.error(CommonUtil.getStackTrace(e));
	        }
	    
		return xmlString;
	}
	
	public static String dateTimeToString(Calendar input) {
		String output = null;
		try {
			if(input != null) {
				output = (new SimpleDateFormat(GlobalConstant.DATE_TIME_FORMAT_INTERFACE)).format(input.getTime());
			}
		} catch (NullPointerException e) {
			output = null;
		}catch (Exception e) {
			output = null;
		}
		return output;
	}
	
	public String generalError()
	 {
		 String errXMLString="Error=Format error occuring at FMS: The element type \"fieldValue\" must " +
		 		"be terminated by the matching end-tag \"</fieldValue>\".|"+
		 "<dataInterface>"+
		 "<header>"+
		 "<id>CDGE_FMS_0000003</id>"+
		 "<from>AIMS</from>"+
		 "<to>FMS</to>"+
		 "<interfaceType>AIMS_FMS_UPDATE_DRIVER</interfaceType>"+
		 "<sentTime>Mon Dec 13 15:21:33 GMT+08:00 2010</sentTime>"+
		 "<numOfEntries>1</numOfEntries>"+
		 "<deliveryMode>synchronously</deliveryMode>"+
		 "<concurrency>true</concurrency>"+
		 "</header>"+
		 "<content>"+
		 "<contentItem>"+
		 "<field>"+
		 "<fieldName>driverIc</fieldName>"+
		 "<fieldValue>S7667190G</fieldValue>"+
		 "</field>"+
		 "<field>"+
		 "<fieldName>contactNo</fieldName>"+
		 "<fieldValue>91835668</fieldValue>"+
		 "</field>"+
		 "<field>"+
		 "<fieldName>email</fieldName>"+
		 "<fieldValue>parasu@info-lab.com<fieldValue>"+
		 "</field>"+
		 "</contentItem>"+
		 "</content>"+
		 "</dataInterface>";
		 return errXMLString;
	 }
	 
	 public String processedError()
	 {
		 String errXMLString1 = "<dataInterface>" +
		 "<header>" +
		     "<id>CDGE_FMS_0003434</id>" +
		     "<from>ABC</from>" +
		     "<to>DEF</to>" +
		     "<interfaceType>FMS_FSM_UPDATE_VEHICLES_SCRAP_DATE</interfaceType>" +
		     "<sentTime>17/09/2010 16:16:28</sentTime>" +
	         "<numOfEntries>1</numOfEntries>" +
		     "<deliveryMode>synchronously</deliveryMode>" +
		     "<concurrency>false</concurrency>" +
		"</header>" +
		"<content>" +
		   "<contentItem>" +
		      "<field>" +
		        "<fieldName>stage</fieldName>" +
		        "<fieldValue>F</fieldValue>" +
		      "</field>" +
		      "<field>" +
		      	"<fieldName>entity</fieldName>" +
		      	"<fieldValue>CCPL</fieldValue>" +
		      "</field>" +
		      "<field>" +
		      	"<fieldName>vehRegNo</fieldName>" +
		      	"<fieldValue>SHA8092G</fieldValue>" +
		      "</field>" +
		      "<field>" +
		      	"<fieldName>vehScrapDt</fieldName>" +
		      	"<fieldValue>30/09/2010</fieldValue>" +
		      "</field>" +
		      "<field>" +
		      	"<fieldName>vehScrapSubmDt</fieldName>" +
		      	"<fieldValue>02/09/2010</fieldValue>" +
		      "</field>" +
		    "</contentItem>" +
		    "<contentItem>"+
		    "<field>"+
		    "<fieldName>Error</fieldName>"+
		    "<fieldValue>|SQL Error: unable to update driver info</fieldValue>"+
		    "</field>"+
		    "</contentItem>"+
		 "</content>" +
	"</dataInterface>";
		 
	return errXMLString1;
	 }
	 
	 public String ack()
	 {
		String ackMsg="<dataInterface>" +
		 "<header>" +
		     "<id>FMS_FSM_0003434</id>" +
		     "<from>ABC</from>" +
		     "<to>DEF</to>" +
		     "<interfaceType>FMS_FSM_UPDATE_VEHICLES_SCRAP_DATE</interfaceType>" +
		     "<sentTime>17/09/2010 16:16:28</sentTime>" +
	         "<numOfEntries>1</numOfEntries>" +
		     "<deliveryMode>synchronously</deliveryMode>" +
		     "<concurrency>true</concurrency>" +
		"</header>" +
		"<content>" +
		   "<contentItem>" +
		      "<field>" +
		        "<fieldName>status</fieldName>" +
		        "<fieldValue>Data Received</fieldValue>" +
		      "</field>" +
		    "</contentItem>"+
		 "</content>" +
	"</dataInterface>";
	return ackMsg;
	}
	 
	public String finalOutput()
	{
		String fOutput="<dataInterface>" +
		 "<header>" +
		     "<id>FMS_FSM_0003434</id>" +
		     "<from>ABC</from>" +
		     "<to>DEF</to>" +
		     "<interfaceType>FMS_FSM_UPDATE_VEHICLES_SCRAP_DATE</interfaceType>" +
		     "<sentTime>17/09/2010 16:16:28</sentTime>" +
	         "<numOfEntries>1</numOfEntries>" +
		     "<deliveryMode>synchronously</deliveryMode>" +
		     "<concurrency>false</concurrency>" +
		"</header>" +
		"<content>" +
		   "<contentItem>" +
		   "<field>" +
	      	"<fieldName>vehScrapDt</fieldName>" +
	      	"<fieldValue>30/09/2010</fieldValue>" +
	      "</field>" +
		   "<field>" +
	      	"<fieldName>entity</fieldName>" +
	      	"<fieldValue>CCPL</fieldValue>" +
	      "</field>" +
		      "<field>" +
		        "<fieldName>status</fieldName>" +
		        "<fieldValue>success</fieldValue>" +
		      "</field>" +
		    "</contentItem>"+
		 "</content>" +
	"</dataInterface>";
	return fOutput;
	}
	
	public String loadXMLFromString(String xmlString) throws Exception 
    { 
		
	 String fieldValue="";
	 String fieldName="";
	
        try {
        	
        	String gErr=xmlString.substring(0,5);
        	if(gErr.equalsIgnoreCase("Error"))
        	{
        		fieldValue="General Error";
        	}
        	else
        	{
        	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
 	        DocumentBuilder builder = factory.newDocumentBuilder(); 
 	        InputSource is = new InputSource(new StringReader(xmlString)); 
 	        DocumentBuilder dBuilder = factory.newDocumentBuilder();
 	        Document doc = dBuilder.parse(is);
 	        	            
            doc.getDocumentElement().normalize();
         
           logger.info("Root element :" + doc.getDocumentElement().getNodeName());
            NodeList nList = doc.getElementsByTagName("field");
           logger.info("-----------------------"+nList);
         
            for (int temp = 0; temp < nList.getLength(); temp++) {
         
               Node nNode = nList.item(temp);	    
               if (nNode.getNodeType() == Node.ELEMENT_NODE) {
         
                  Element eElement = (Element) nNode;
               
                  
                  
                  if(getTagValue("fieldName",eElement).equalsIgnoreCase("status") )
                  {
                	  logger.info("****************************************");
                	fieldName=getTagValue("fieldName",eElement);
                	fieldValue=getTagValue("fieldValue",eElement);
                	logger.info("fieldName>>>>"+fieldName);
                	logger.info("fieldValue>>>>"+fieldValue);
                	  logger.info("****************************************");
                	
                  }
                  else if(getTagValue("fieldName",eElement).equalsIgnoreCase("Error"))
                  {
                	  logger.error("****************************************");
                	    fieldName=getTagValue("fieldName",eElement);
	                	//fieldValue=getTagValue("fieldValue",eElement);
	                	fieldValue="Unsuccessful";
	                	logger.error("fieldName>>>>"+fieldName);
	                	logger.error("fieldValue>>>>"+fieldValue);
	                	  logger.error("****************************************");
	                	
                  }
                
                }
            }
        }
          } catch (Exception e) {
            logger.error(CommonUtil.getStackTrace(e));
          }
       return fieldValue;
    } 
 private String getTagValue(String sTag, Element eElement){
     NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes();
     Node nValue = (Node) nlList.item(0); 
  
     return nValue.getNodeValue();    
  }

 public void updateInterfacePartReplacements() {
		
		logger.info("Starting intf updateInterfacePartReplacements" );
		logger.info("--------------------------Executing intf updateInterfacePartReplacements-------------------------------------------------");
		
		String autoSeqID="";
		Query query = em.createQuery("from IntfPartReplacement where status is null");
		List<IntfPartReplacement> intfPartReplacementList = query.getResultList();
		logger.info(".... Inside updateInterfacePartReplacements -- intfPartReplacementList.size() >>>"+intfPartReplacementList.size());
		logger.info("Total number of Part Replacements="+intfPartReplacementList.size());
	
		
		
		if(intfPartReplacementList.size() > 0)
		{
			try {
				Integer nextVal = (Integer) em.createNativeQuery("select nextval('AMSQ_INTF_PARTREPLACE_HEADERID') from dual").getSingleResult();
				autoSeqID = nextVal.toString();
				for(int i=autoSeqID.length();i<7;i++)
				{
					autoSeqID="0"+autoSeqID;
				}
				autoSeqID="AIMS_FMS_"+autoSeqID;
			} catch (Exception e) {
				
				logger.error(CommonUtil.getStackTrace(e));
			}
			logger.info("Sequence ID="+autoSeqID);
			
			String xmlInput=generatePartReplacementXML(intfPartReplacementList,autoSeqID);
		
			String xmlOutput ="";
			
			try{
				
			if(!fmsInterfaceUrl.equalsIgnoreCase("") && fmsInterfaceUrl != null)
			{
				MediatorDataInterfaceImpl service = new MediatorDataInterfaceImpl_Impl(fmsInterfaceUrl);
				MediatorDataInterfaceImplPort port = service.getMediatorDataInterfaceImplPort();
				xmlOutput = port.processInfo("storeInfo", xmlInput);
				 
				 	//String xmlOutput = processedError();
					//String xmlOutput = finalOutput();
				    //String xmlOutput = generalError();
				    //String xmlOutput = ack();
				 
					IntfPartReplacement intfPartReplacement=null;
					
					try {
						String fmsUpdateStatus = loadXMLFromString(xmlOutput);
										
						//Successfully received acknowledgment
						if(fmsUpdateStatus.equalsIgnoreCase("Data Received"))
						{
							logger.info("..updateInterfacePartReplacements - Successfully received Acknowledgement from FMS..");
						}
			    		//successfully updated into FMS
						else if(fmsUpdateStatus.equalsIgnoreCase("success"))
						{
						  
						  for(int i=0;i<intfPartReplacementList.size();i++)
						  {
							  intfPartReplacement = new IntfPartReplacement();
							  intfPartReplacement = (IntfPartReplacement)intfPartReplacementList.get(i);
							  IntfPartReplacement newIntfPartReplacement = em.find(IntfPartReplacement.class, intfPartReplacement.getIntfPartReplacementId());						
							  intfPartReplacement.setStatus(GlobalConstant.SUCCESS_VALUE);	
							  intfPartReplacement.setDateExecuted(new Date());
							  BeanUtils.copyProperties(intfPartReplacement,newIntfPartReplacement);						
							  em.merge(newIntfPartReplacement);	
							
						  }
						 				  
						  logger.info("...updateInterfacePartReplacements - Update Successfully to FMS....");
						}
						//process error
						else if(fmsUpdateStatus.equalsIgnoreCase("Unsuccessful"))
						{
							logger.error("updateInterfacePartReplacements - Process Error,update Unsuccessful.");
							logger.error("updateInterfacePartReplacements - Here's the incoming xml from FMS:\n\n" + xmlOutput);
							
							for(int i=0;i<intfPartReplacementList.size();i++)
							  {
								  intfPartReplacement = new IntfPartReplacement();
								  intfPartReplacement = (IntfPartReplacement)intfPartReplacementList.get(i);
								  IntfPartReplacement newIntfPartReplacement = em.find(IntfPartReplacement.class, intfPartReplacement.getIntfPartReplacementId());						
								  intfPartReplacement.setStatus(GlobalConstant.FAILURE_VALUE);	
								  
								  BeanUtils.copyProperties(intfPartReplacement,newIntfPartReplacement);						
								  em.merge(newIntfPartReplacement);	
								
							  }
							
						}
						//General Error
						else if(fmsUpdateStatus.equalsIgnoreCase("General Error"))
						{
							logger.error("updateInterfacePartReplacements - General Error,update Unsuccessful.");
							logger.error("updateInterfacePartReplacements - Here's the incoming xml from FMS:\n\n" + xmlOutput);
							
							for(int i=0;i<intfPartReplacementList.size();i++)
							  {
								  intfPartReplacement = new IntfPartReplacement();
								  intfPartReplacement = (IntfPartReplacement)intfPartReplacementList.get(i);
								  IntfPartReplacement newIntfPartReplacement = em.find(IntfPartReplacement.class, intfPartReplacement.getIntfPartReplacementId());						
								  intfPartReplacement.setStatus(GlobalConstant.FAILURE_VALUE);	
								  
								  BeanUtils.copyProperties(intfPartReplacement,newIntfPartReplacement);						
								  em.merge(newIntfPartReplacement);	
								
							  }
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						logger.error(CommonUtil.getStackTrace(e));
					}
			}
			
			else
			{
				logger.error("updateInterfacePartReplacements - Pls do check the FMS Interface Url. It is blank and not having a valid URL.");
			}
			
		}
			catch (IOException e) {
				// TODO Auto-generated catch block
				logger.error(CommonUtil.getStackTrace(e));
			} catch (ServiceException e) {
				// TODO Auto-generated catch block
				logger.error(CommonUtil.getStackTrace(e));
			}
			catch (Exception e) {
				// TODO Auto-generated catch block
				logger.error(CommonUtil.getStackTrace(e));
			}
				
			
			
			
		
		}
		else
		{
			logger.info("There is no new parts replacement detail record from AIMS to update in FMS...");
		}
		
		logger.info("--------------------------Exiting intf updateInterfacePartReplacements-------------------------------------------------");
	}
 
 
 public String generatePartReplacementXML(List<IntfPartReplacement> intfPartReplacementList,String autoUnitSeqID)
	{
	 
	  String xmlString = "";
				
		 try {
	          
			 IntfPartReplacement intfPartReplacement=new IntfPartReplacement();
	            //Creating an empty XML Document

	            //We need a Document
	            DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
	            DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
	            Document doc = docBuilder.newDocument();
	           
	            //Creating the XML tree

	            //create the root element and add it to the document
	            Element root = doc.createElement("dataInterface");
	            doc.appendChild(root);

	           

	            //create child element, add an attribute, and add to root
	            Element header = doc.createElement("header");
	            root.appendChild(header);
	            
	            Element id=doc.createElement("id");
	            header.appendChild(id);
	            Text text = doc.createTextNode(autoUnitSeqID);
	            id.appendChild(text);
	           
	            Element from=doc.createElement("from");
	            header.appendChild(from);
	            text = doc.createTextNode("AIMS");
	            from.appendChild(text);
	            
	            Element to=doc.createElement("to");
	            header.appendChild(to);
	            text = doc.createTextNode("FMS");
	            to.appendChild(text);
	            
	            Element interfaceType=doc.createElement("interfaceType");
	            header.appendChild(interfaceType);
	            text = doc.createTextNode("AIMS_FMS_ASSET_PARTS_REPLACEMENT");
	            interfaceType.appendChild(text);
	            
	            Calendar cal=Calendar.getInstance();
	            
	            Element sentTime=doc.createElement("sentTime");
	            header.appendChild(sentTime);
	            text = doc.createTextNode(dateTimeToString(cal));
	            sentTime.appendChild(text);
	            
	            Element numOfEntries=doc.createElement("numOfEntries");
	            header.appendChild(numOfEntries);
	            text = doc.createTextNode(""+intfPartReplacementList.size());
	            numOfEntries.appendChild(text);
	            
	            Element deliveryMode=doc.createElement("deliveryMode");
	            header.appendChild(deliveryMode);
	            text = doc.createTextNode("synchronously");
	            deliveryMode.appendChild(text);
	            
	            Element concurrency=doc.createElement("concurrency");
	            header.appendChild(concurrency);
	            text = doc.createTextNode("true");
	            concurrency.appendChild(text);
	            
	            Element content = doc.createElement("content");
	            root.appendChild(content);
	            intfPartReplacement=new IntfPartReplacement();
	            for(int i=0;i<intfPartReplacementList.size();i++)
	            {
				            intfPartReplacement=(IntfPartReplacement)intfPartReplacementList.get(i);
				            
				            Element contentItem=doc.createElement("contentItem");
				            content.appendChild(contentItem);
				            
				            Element field=doc.createElement("field");
				            contentItem.appendChild(field);
				            
				            Element fieldName=doc.createElement("fieldName");
				            field.appendChild(fieldName);
				            text = doc.createTextNode("vehRegnNo");
				            fieldName.appendChild(text);
				            
				            Element fieldValue=doc.createElement("fieldValue");
				            field.appendChild(fieldValue);
				            text = doc.createTextNode(intfPartReplacement.getVehicleId());
				            fieldValue.appendChild(text);
				            
				            Element field1=doc.createElement("field");
				            contentItem.appendChild(field1);
				            
				            Element fieldName1=doc.createElement("fieldName");
				            field1.appendChild(fieldName1);
				            text = doc.createTextNode("model");
				            fieldName1.appendChild(text);
				            
				            Element fieldValue1=doc.createElement("fieldValue");
				            field1.appendChild(fieldValue1);
				            text = doc.createTextNode(intfPartReplacement.getAssetModelCode());
				            fieldValue1.appendChild(text);
				            
				            Element field3=doc.createElement("field");
				            contentItem.appendChild(field3);
				            
				            Element fieldName2=doc.createElement("fieldName");
				            field3.appendChild(fieldName2);
				            text = doc.createTextNode("oldSerialNo");
				            fieldName2.appendChild(text);
				            
				            Element fieldValue2=doc.createElement("fieldValue");
				            field3.appendChild(fieldValue2);
				            text = doc.createTextNode(intfPartReplacement.getOldSerialNo()!=null?intfPartReplacement.getOldSerialNo():"");
				            fieldValue2.appendChild(text);
				            
				            Element field4=doc.createElement("field");
				            contentItem.appendChild(field4);
				            
				            Element fieldName4=doc.createElement("fieldName");
				            field4.appendChild(fieldName4);
				            text = doc.createTextNode("newSerialNo");
				            fieldName4.appendChild(text);
				            
				            Element fieldValue4=doc.createElement("fieldValue");
				            field4.appendChild(fieldValue4);
				            text = doc.createTextNode(intfPartReplacement.getNewSerialNo());
				            fieldValue4.appendChild(text);
	            
	            }
	         
	            //Output the XML

	            //set up a transformer
	            TransformerFactory transfac = TransformerFactory.newInstance();
	            Transformer trans = transfac.newTransformer();
	            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
	            trans.setOutputProperty(OutputKeys.INDENT, "yes");

	            //create string from xml tree
	            StringWriter sw = new StringWriter();
	            StreamResult result = new StreamResult(sw);
	            DOMSource source = new DOMSource(doc);
	            trans.transform(source, result);
	            xmlString = sw.toString();

	            //print xml
	           logger.info("Here's the xml:\n\n" + xmlString);

	        } catch (Exception e) {
	        	logger.error(CommonUtil.getStackTrace(e));
	        }
	    
		return xmlString;
	}
 
 
	public void updateInterfaceTaxiDowntime() {
		
		
		logger.info("Starting intf updateInterfaceTaxiDowntime" );		
		logger.info("--------------------------Executing intf updateInterfaceTaxiDowntime-------------------------------------------------");
		
		String autoSeqID="";
		Query query = em.createQuery("from IntfTaxiDowntime where status is null");
		List<IntfTaxiDowntime> intfTaxiDowntimeList = query.getResultList();
		logger.info(".... Inside updateInterfaceTaxiDowntime -- intfTaxiDowntimeList.size() >>>"+intfTaxiDowntimeList.size());
		logger.info("Total number of Taxi Downtime events="+intfTaxiDowntimeList.size());
		
		
		
		if(intfTaxiDowntimeList.size() > 0)
		{
			try {
				Integer nextVal = (Integer) em.createNativeQuery("select nextval('AMSQ_INTF_DOWNTIME_HEADERID') from dual").getSingleResult();
				autoSeqID = nextVal.toString();
				for(int i=autoSeqID.length();i<7;i++)
				{
					autoSeqID="0"+autoSeqID;
				}
				autoSeqID="AIMS_FMS_"+autoSeqID;
			} catch (Exception e) {
				
				logger.error(CommonUtil.getStackTrace(e));
			}
			logger.info("Sequence ID="+autoSeqID);
			
			String xmlInput=generateTaxiDowntimeXML(intfTaxiDowntimeList,autoSeqID);
			
			String xmlOutput ="";
			
			try{				
				
				if(!fmsInterfaceUrl.equalsIgnoreCase("") && fmsInterfaceUrl != null)
				{
						
						MediatorDataInterfaceImpl service = new MediatorDataInterfaceImpl_Impl(fmsInterfaceUrl);
						MediatorDataInterfaceImplPort port = service.getMediatorDataInterfaceImplPort();
						 xmlOutput = port.processInfo("storeInfo", xmlInput);
						 
						    //String xmlOutput = processedError();
							//String xmlOutput = finalOutput();
						    //String xmlOutput = generalError();
						    //String xmlOutput = ack();
							
							IntfTaxiDowntime intfTaxiDowntime=null;
							try {
								String fmsUpdateStatus = loadXMLFromString(xmlOutput);
												
								//Successfully received acknowledgment
								if(fmsUpdateStatus.equalsIgnoreCase("Data Received"))
								{
									logger.info(".. updateInterfaceTaxiDowntime - Successfully received Acknowledgement from FMS..");
								}
					    		//successfully updated into FMS
								else if(fmsUpdateStatus.equalsIgnoreCase("success"))
								{
								  
								  for(int i=0;i<intfTaxiDowntimeList.size();i++)
								  {
									  intfTaxiDowntime = (IntfTaxiDowntime)intfTaxiDowntimeList.get(i);
									  intfTaxiDowntime = em.find(IntfTaxiDowntime.class, intfTaxiDowntime.getIntfTaxiDowntimeId());						
									  intfTaxiDowntime.setStatus(GlobalConstant.SUCCESS_VALUE);
									  intfTaxiDowntime.setDateExecuted(new Date());						
									  em.merge(intfTaxiDowntime);	
									  
								  }
								 				  
								  logger.info("...updateInterfaceTaxiDowntime - Update Successfully to FMS....");
								}
								//process error
								else if(fmsUpdateStatus.equalsIgnoreCase("Unsuccessful"))
								{
									logger.error("updateInterfaceTaxiDowntime - Process Error,update Unsuccessful.");
									logger.error("updateInterfaceTaxiDowntime - Here's the incoming xml from FMS:\n\n" + xmlOutput);
									
									for(int i=0;i<intfTaxiDowntimeList.size();i++)
									  {
										  intfTaxiDowntime = (IntfTaxiDowntime)intfTaxiDowntimeList.get(i);
										  intfTaxiDowntime = em.find(IntfTaxiDowntime.class, intfTaxiDowntime.getIntfTaxiDowntimeId());						
										  intfTaxiDowntime.setStatus(GlobalConstant.FAILURE_VALUE);
										  em.merge(intfTaxiDowntime);	
										  
									  }
								}
								//General Error
								else if(fmsUpdateStatus.equalsIgnoreCase("General Error"))
								{
									logger.error("updateInterfaceTaxiDowntime - General Error,update Unsuccessful.");
									logger.error("updateInterfaceTaxiDowntime - Here's the incoming xml from FMS:\n\n" + xmlOutput);
									for(int i=0;i<intfTaxiDowntimeList.size();i++)
									  {
										  intfTaxiDowntime = (IntfTaxiDowntime)intfTaxiDowntimeList.get(i);
										  intfTaxiDowntime = em.find(IntfTaxiDowntime.class, intfTaxiDowntime.getIntfTaxiDowntimeId());						
										  intfTaxiDowntime.setStatus(GlobalConstant.FAILURE_VALUE);
										  em.merge(intfTaxiDowntime);	
										  
									  }
								}
							} catch (Exception e) {
								// TODO Auto-generated catch block
								logger.error(CommonUtil.getStackTrace(e));
							}					
			}
			else{
				logger.error("updateInterfaceTaxiDowntime - Pls check FMS Interface Url. It is blank and not having a valid URL.");					
			}
		}
			
			catch (IOException e) {
				// TODO Auto-generated catch block
				logger.error(CommonUtil.getStackTrace(e));
			} catch (ServiceException e) {
				// TODO Auto-generated catch block
				logger.error(CommonUtil.getStackTrace(e));
			}
			catch (Exception e) {
				// TODO Auto-generated catch block
				logger.error(CommonUtil.getStackTrace(e));
			}
				
			
			
	}
		
		else
		{
			logger.info("There is no data for Taxi Downtime from AIMS to update into FMS...");
		}
		
		logger.info("--------------------------Exiting intf updateInterfaceTaxiDowntime-------------------------------------------------");
	
 }
	
	public String generateTaxiDowntimeXML(List<IntfTaxiDowntime> intfTaxiDowntimeList,String autoSeqID)
	{
		
		String xmlString ="";
				
		 try {
	            
			 IntfTaxiDowntime intfTaxiDowntime= null;
	            //Creating an empty XML Document

	            //We need a Document
	            DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
	            DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
	            Document doc = docBuilder.newDocument();
	           
	            //Creating the XML tree

	            //create the root element and add it to the document
	            Element root = doc.createElement("dataInterface");
	            doc.appendChild(root);

	          
	            //create child element, add an attribute, and add to root
	            Element header = doc.createElement("header");
	            root.appendChild(header);
	            
	            Element id=doc.createElement("id");
	            header.appendChild(id);
	            Text text = doc.createTextNode(autoSeqID);
	            id.appendChild(text);
	           
	            Element from=doc.createElement("from");
	            header.appendChild(from);
	            text = doc.createTextNode("AIMS");
	            from.appendChild(text);
	            
	            Element to=doc.createElement("to");
	            header.appendChild(to);
	            text = doc.createTextNode("FMS");
	            to.appendChild(text);
	            
	            Element interfaceType=doc.createElement("interfaceType");
	            header.appendChild(interfaceType);
	            text = doc.createTextNode("AIMS_FMS_UPDATE_TAXI_DOWNTIME");
	            interfaceType.appendChild(text);
	            
	            Calendar cal=Calendar.getInstance();
	            
	            Element sentTime=doc.createElement("sentTime");
	            header.appendChild(sentTime);
	            text = doc.createTextNode(dateTimeToString(cal));
	            sentTime.appendChild(text);
	            
	            Element numOfEntries=doc.createElement("numOfEntries");
	            header.appendChild(numOfEntries);
	            text = doc.createTextNode(""+intfTaxiDowntimeList.size());
	            numOfEntries.appendChild(text);
	            
	            Element deliveryMode=doc.createElement("deliveryMode");
	            header.appendChild(deliveryMode);
	            text = doc.createTextNode("synchronously");
	            deliveryMode.appendChild(text);
	            
	            Element concurrency=doc.createElement("concurrency");
	            header.appendChild(concurrency);
	            text = doc.createTextNode("true");
	            concurrency.appendChild(text);
	            
	            Element content = doc.createElement("content");
	            root.appendChild(content);
	            intfTaxiDowntime=new IntfTaxiDowntime();
	            for(int i=0;i<intfTaxiDowntimeList.size();i++)
	            {
	            	intfTaxiDowntime=(IntfTaxiDowntime)intfTaxiDowntimeList.get(i);
	            
	            Element contentItem=doc.createElement("contentItem");
	            content.appendChild(contentItem);
	            
	            Element field=doc.createElement("field");
	            contentItem.appendChild(field);
	            
	            Element fieldName=doc.createElement("fieldName");
	            field.appendChild(fieldName);
	            text = doc.createTextNode("vehRegnNo");
	            fieldName.appendChild(text);
	            
	            Element fieldValue=doc.createElement("fieldValue");
	            field.appendChild(fieldValue);
	            text = doc.createTextNode(intfTaxiDowntime.getVehicleId());
	            fieldValue.appendChild(text);
	            
	            Element field1=doc.createElement("field");
	            contentItem.appendChild(field1);
	            
	            Element fieldName1=doc.createElement("fieldName");
	            field1.appendChild(fieldName1);
	            text = doc.createTextNode("startDt");
	            fieldName1.appendChild(text);
	            
	            Element fieldValue1=doc.createElement("fieldValue");
	            field1.appendChild(fieldValue1);
	            text = doc.createTextNode(intfTaxiDowntime.getStartTimeForXml());
	            fieldValue1.appendChild(text);
	            
	            Element field3=doc.createElement("field");
	            contentItem.appendChild(field3);
	            
	            Element fieldName2=doc.createElement("fieldName");
	            field3.appendChild(fieldName2);
	            text = doc.createTextNode("endDt");
	            fieldName2.appendChild(text);
	            
	            Element fieldValue2=doc.createElement("fieldValue");
	            field3.appendChild(fieldValue2);
	            text = doc.createTextNode(intfTaxiDowntime.getEndTimeForXml());
	            fieldValue2.appendChild(text);
	            }
	           
	            //Output the XML

	            //set up a transformer
	            TransformerFactory transfac = TransformerFactory.newInstance();
	            Transformer trans = transfac.newTransformer();
	            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
	            trans.setOutputProperty(OutputKeys.INDENT, "yes");

	            //create string from xml tree
	            StringWriter sw = new StringWriter();
	            StreamResult result = new StreamResult(sw);
	            DOMSource source = new DOMSource(doc);
	            trans.transform(source, result);
	             xmlString = sw.toString();

	            //print xml
	           logger.info("Here's the xml:\n\n" + xmlString);

	        } catch (Exception e) {
	           logger.info("error:", e);
	        }
	    
		return xmlString;
	}

	public void updateTableSequence() {
		
		logger.info("Starting updateTableSequence scheduler" );
		Query query = em.createNativeQuery("{ call ampk_gen_util.reset_sequence('AMSQ_CT_WORKORDER') }");
		query.executeUpdate();
		
		query = em.createNativeQuery("{ call ampk_gen_util.reset_sequence('AMSQ_CT_TRANSACTION_CODE') }");
		query.executeUpdate();
		
		query = em.createNativeQuery("{ call ampk_gen_util.reset_sequence('AMSQ_CT_TRANSACTION_GENCODE') }");
		query.executeUpdate();
		
		query = em.createNativeQuery("{ call ampk_gen_util.reset_sequence('AMSQ_CT_ASSETTAG') }");
		query.executeUpdate();
		
		logger.info("End updateTableSequence scheduler" );
	}

	public void createMonthEndClosing() {
		// TODO scheduler month end closing
		Date date = new Date();
		String year = DateFormatUtils.format(date, "yyyy");
		String month = DateFormatUtils.format(date, "MM");
		try{
			assetModelService.createAssetSchedulerBalance(month, year, "SCHEDULER");
			logger.info("Scheduler success message: on " + date);
		}catch(Exception ex){
			logger.error("Scheduler error message: on " + date, ex);
		}
	}
	
}
